import PubSub from 'pubsub-js'
import * as d3 from 'd3'

export default {
  ws: null,
  close: function () {
    if (this.ws) {
      this.ws.close()
    }
  },
  init: function () {
    if (!this.ws) {
      if ('WebSocket' in window) {
        const ws = new WebSocket('ws://localhost:3000')
        ws.onopen = function () {
          console.log('WebSocket 连接成功')
        }

        ws.onclose = function () {
          console.log('WebSocket 连接已关闭')
        }

        ws.onmessage = function (res) {
          if (res !== null) {
            const result = res.data
            PubSub.publish('setPQI', result)
            console.log(JSON.parse(result))
            setPQI('svg', '8000005', JSON.parse(result))
          }
        }

        subscribeInit(ws, 'setPQI')
      }
    } else {
      console.log('浏览器不支持 WebSocket')
    }
  }
}

function subscribeInit (ws, name) {
  PubSub.unsubscribe(name)
  PubSub.subscribeOnce(name, (m, e) => {
    const data = { label: m, value: e }
    ws.send(JSON.stringify(data))
  })
}

function setPQI (data, id, e) {
  const self = d3.select(data)
  const gNodes = self.selectAll('g').select('*[id="' + id + '"]').selectAll('tspan').nodes()
  if (gNodes.length >= 1) {
    if (e.objectId === 8000005) {
      gNodes[0].innerHTML = e.labelP
      gNodes[1].innerHTML = e.labelQ
      gNodes[2].innerHTML = e.labelI
    }
  }
}
